"""
认证路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session

from database import get_db
from schemas.auth import (
    UserRegister,
    UserLogin,
    LoginByCode,
    SendCodeRequest,
    TokenResponse,
    UserInfo,
    DingtalkLogin,
    RefreshTokenRequest,
    RefreshTokenResponse
)
from view.auth_service import AuthService
from routers.dependencies import get_current_user
from models.models import User

router = APIRouter(prefix="/api/auth", tags=["认证"])


@router.post("/register", response_model=UserInfo, status_code=status.HTTP_201_CREATED)
async def register(
    user_data: UserRegister,
    db: Session = Depends(get_db)
):
    """
    用户注册
    """
    user = AuthService.register_user(db, user_data)
    return user


@router.post("/login", response_model=TokenResponse)
async def login_by_password(
    login_data: UserLogin,
    db: Session = Depends(get_db)
):
    """
    账密登录（JWT）
    
    支持用户名或手机号登录
    """
    access_token, refresh_token, user = AuthService.login_by_password(db, login_data)
    
    return TokenResponse(
        access_token=access_token,
        refresh_token=refresh_token,  # 返回Refresh Token用于续命
        token_type="bearer",
        user_id=user.id,
        username=user.username
    )


@router.post("/send-code", status_code=status.HTTP_200_OK)
async def send_code(
    request: SendCodeRequest
):
    """
    发送验证码
    
    发送短信验证码到指定手机号
    """
    success, message = AuthService.send_verification_code(request.phone)
    
    if success:
        return {"message": "验证码发送成功", "code": "success"}
    else:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=message
        )


@router.post("/login-by-code", response_model=TokenResponse)
async def login_by_code(
    login_data: LoginByCode,
    db: Session = Depends(get_db)
):
    """
    验证码登录
    
    通过手机号+验证码登录，首次登录自动注册
    """
    access_token, refresh_token, user = AuthService.login_by_code(db, login_data.phone, login_data.code)
    
    return TokenResponse(
        access_token=access_token,
        refresh_token=refresh_token,  # 返回Refresh Token用于续命
        token_type="bearer",
        user_id=user.id,
        username=user.username
    )


@router.post("/login-by-dingtalk", response_model=TokenResponse)
async def login_by_dingtalk(
    login_data: DingtalkLogin,
    db: Session = Depends(get_db)
):
    """
    钉钉登录
    
    通过钉钉授权码登录，首次登录自动注册
    """
    try:
        access_token, refresh_token, user = await AuthService.login_by_dingtalk(db, login_data.code)
        
        return TokenResponse(
            access_token=access_token,
            refresh_token=refresh_token,  # 返回Refresh Token用于续命
            token_type="bearer",
            user_id=user.id,
            username=user.username
        )
    except HTTPException:
        raise
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"钉钉登录处理失败: {str(e)}"
        )


@router.post("/refresh", response_model=RefreshTokenResponse)
async def refresh_token(request: RefreshTokenRequest, db: Session = Depends(get_db)):
    """刷新Token接口（Token续命）"""
    access_token, refresh_token, user = AuthService.refresh_access_token(db, request.refresh_token)
    return RefreshTokenResponse(
        access_token=access_token,
        refresh_token=refresh_token,  # 返回新的Token对
        token_type="bearer"
    )


@router.get("/me", response_model=UserInfo)
async def get_current_user_info(
    current_user: User = Depends(get_current_user)
):
    """
    获取当前用户信息
    
    需要Bearer Token认证
    """
    return current_user


@router.get("/test-token")
async def test_token(
    current_user: User = Depends(get_current_user)
):
    """
    测试token验证
    
    调试用接口
    """
    return {
        "success": True,
        "user_id": current_user.id,
        "username": current_user.username,
        "message": "Token验证成功"
    }


@router.post("/debug-token")
async def debug_token(
    credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())
):
    """
    调试token接口 - 详细输出token验证过程
    """
    from tools.auth import verify_token
    
    token = credentials.credentials
    
    result = {
        "token_received": True,
        "token_length": len(token),
        "token_preview": token[:30] + "...",
    }
    
    # 尝试解析 token payload（不验证签名）
    try:
        parts = token.split('.')
        if len(parts) == 3:
            import base64
            import json
            payload_b64 = parts[1]
            payload = json.loads(base64.urlsafe_b64decode(payload_b64 + '=='))
            result["payload"] = payload
            result["user_id_in_token"] = payload.get("sub")
            result["expires_at"] = payload.get("exp")
            result["expires_datetime"] = str(payload.get("exp") and payload.get("exp") * 1000)
        else:
            result["error"] = "Invalid JWT format"
    except Exception as e:
        result["parse_error"] = str(e)
    
    # 尝试验证 token
    payload = verify_token(token)
    if payload:
        result["verification"] = "success"
        result["verified_user_id"] = payload.get("sub")
    else:
        result["verification"] = "failed"
        
        # 尝试手动验证以获取详细错误
        from jose import JWTError, jwt
        from config import settings
        try:
            decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
            result["manual_verification"] = "success"
        except JWTError as e:
            result["manual_verification"] = f"failed: {str(e)}"
        except Exception as e:
            result["manual_verification"] = f"error: {type(e).__name__}: {str(e)}"
    
    result["secret_key_preview"] = settings.SECRET_KEY[:20] + "..."
    
    return result

